package ViewPropertyPanel;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JButton;

import resource.ResourceManager;

import drawPropertyCommands.IDrawModifier;


/**
 * 
 * My attempt at using reflection and factory method to refactor ViewPropertyToolBar.
 * However, I didn't have enough time to debug it.
 * @author KevinWang
 *
 */
public class ButtonFactory {
    
    private static ResourceManager buttonResources = ResourceManager.getInstance();

    public ButtonFactory(){
        buttonResources.addResourcesFromFile("Buttons");
    }
    public void addButton(){
        ArrayList<JButton> resultList = new ArrayList<JButton>();
        String[] buttonTypes = buttonResources.getStringArray("Types");
        String imageSource = buttonResources.getString("ImageSource");
        String drawModifierSource = buttonResources.getString("TypeSource");

        Class cls = null;

        for(String type : buttonTypes){
            String methodCall = buttonResources.getString(type+".methodCall");
            cls=buttonResources.getClass();
            Method method=null;
            try {
                method = cls.getDeclaredMethod(methodCall, String.class);
            } catch (Exception e) {
                e.printStackTrace();
            } 
            String[] buttonList = buttonResources.getStringArray(type+".buttonList");
            Object argument = null;
            for(String button : buttonList){
                try {
                    argument =method.invoke(buttonResources, button+".argument" );
                } catch (Exception e) {
                    e.printStackTrace();
                }

                String imageName = buttonResources.getString(button+".icon");
                ImageIcon icon = new ImageIcon(imageSource+imageName);
                Class<?> modifierClass=null;
                IDrawModifier modifier=null;
                try {
                    modifierClass = Class.forName(drawModifierSource+"."+type);
                    Class<?> modifierArgumentClass = Class.forName("java.lang."+methodCall.replaceFirst("get", ""));
                    Constructor<?> modifierConstructor = modifierClass.getConstructor(modifierArgumentClass);
                    modifier = (IDrawModifier) modifierConstructor.newInstance(argument);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                resultList.add(new DrawModifierButtons(modifier, button, null, icon));

            }
        }
    }
}